<?php

namespace Admin\Controller;

class YardController extends AdminController {

    public function index() {

        $keywords = I('keywords');
        $where['y.is_del'] = 0;
        if ($keywords) {
            $where['yard_name'] = array('like', "%{$keywords}%");
            $this->assign('keywords', $keywords);
        }

        $M = M()->table("ot_yard as y")
                ->join('ot_dock AS d on y.dock_id = d.dock_id')
                ->join('ot_port AS p on d.port_id = p.port_id');
        $field = 'y.*,d.dock_name,p.port_name';
        $order = "y.yard_id desc";
        $list = $this->lists($M, $where, $order, $field);

        $this->assign('_list', $list);
        $this->display();
    }

    public function add() {
        $id = I('id', 0, 'intval');
        if (IS_POST) {
            $dock_id = I('dock_id', 0, 'intval');
            $yard_name = I('yard_name');
            $yard_price = I('yard_price', 0);

            if ($dock_id == 0) {
                $this->error('必须选择码头');
            }

            if (empty($yard_name)) {
                $this->error('堆场名称必须填写');
            }

            $data['dock_id'] = $dock_id;
            $data['yard_name'] = $yard_name;
            $data['yard_price'] = $yard_price;

            $result = 0;
            if ($id == 0) {
                $result = M('Yard')->add($data);
            } else {
                $result = M('Yard')->where(['yard_id' => $id])->save($data);
            }

            if ($result) {
                $this->success('操作成功', U('index'));
            } else {
                $this->error('操作失败');
            }
        } else {

            if ($id != 0) {
                $data = M('Yard')
                                ->table('ot_yard as y')
                                ->field('y.*,d.port_id')
                                ->join('ot_dock AS d on y.dock_id = d.dock_id')
                                ->join('ot_port AS p on d.port_id = p.port_id')
                                ->where(array('yard_id' => $id))->find();
                $dlist = M('Dock')->where(['port_id' => $data['port_id'], 'is_del' => 0])->select();
                $this->assign('dlist', $dlist);
                $this->assign('data', $data);
            }

            $plist = M('Port')->select();


            $this->assign('plist', $plist);
            $this->display();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('请选择堆场');
        }

        $res = M('Yard')->where(array('yard_id' => $id))->save(['is_del' => 1]);

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function getDockByPortId() {
        $id = I('id', 0, 'intval');
        $dlist = M('Dock')->field('dock_id,dock_name')->where(['port_id' => $id, 'is_del' => 0])->select();
        $this->success('获取成功', $dlist);
    }

}
